<?php

/**
 * Created by PhpStorm.
 * User: yutongfu
 * Date: 2019/6/26
 * Time: 10:01 AM
 */
class Timer
{
    private $serv;

    public function __construct()
    {
//构建Server对象
        $this->serv = new Swoole\Server('0.0.0.0', 9501, SWOOLE_BASE, SWOOLE_SOCK_TCP);
        //设置运行时参数
        $this->serv->set([
            'work_num' => 8,
            'daemonize' => false,
            'max_request' => 10000,
            'dispatcg' => 2,
            'debug_mode' => 1
        ]);
        echo 11111;
        //注册事件回调函数
        $this->serv->on('Start', [$this, 'onStart']);
        $this->serv->on('WorkerStart', [$this, 'onWorkerStart']);
        $this->serv->on('Connect', [$this, 'onConnect']);
        $this->serv->on('Receive', [$this, 'onReceive']);
        $this->serv->on('Close', [$this, 'onClose']);
        $this->serv->start();
    }

    public function onStart($serv)
    {
        echo "Start\n";
    }

    public function onConnect($serv, $fd, $from_id)
    {
        echo "Client {$fd} connect\n";
    }

    public function onClose($serv, $fd, $from_id)
    {
        echo "Client {$fd} close connect\n";
    }

    public function onWorkerStart($serv, $worker_id)
    {
        echo "onWorkerStart\n";
        if ($worker_id == 0) {
            swoole_timer_tick(1000, function () {
                echo "Timer running\n";
                swoole_timer_tick(3000, function () {
                    echo "after 3000ms\n";
                });
            });
        }

    }

    public function onReceive(swoole_server $serv, $fd, $form_id, $data)
    {
        echo "Get Message From Client {$fd}:{$data}\n";

        swoole_timer_after(10000, function () use ($serv, $fd) {
            echo "Timer after";
            $this->serv->send($fd, 'hello after'); //10秒后向客户端发送

        });
    }

    public function onTick($timer_id, $parames = null)
    {
        echo "Timer {$timer_id} running\n";
        echo "parames {$parames} \n";
    }


}

$server = new Timer();